import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Form,
    Input,
    DatePicker,
    Select,
    Button,
    Card,
    InputNumber,
    Radio,
    Icon,
    Tooltip,
    Table,
    Modal,
    Slider,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './style.less';
import GoodsModal from './GoodsModal';
import {Link} from 'dva/router';
import G from '../../utils/g';
import moment from 'moment';

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;

@connect(({loading}) => ({
    submitting: loading.effects['form/submitRegularForm'],
}))
@Form.create()
export default class BasicForms extends PureComponent {
    state = {
        modalVisible: false,
        rowSelection: [],
        selectedGoods: [], //选中的商品列表
        detail: {
            rule: {
                licence: {},
                threshold: {},
            },
        }, //用于保存修改时传回的数据

    };

    componentDidMount() {
        const {dispatch, location} = this.props;
        this.id = G.getUrlValue('id', location.search);
        if (typeof this.id != 'undefined') {
            dispatch({
                type: 'coupon/getDetail',
                payload: {
                    id: this.id
                }
            }).then((res)=> {
                console.log(res);
                //this.setState(newState);

                this.setState({
                    detail: res,
                    selectedGoods: res.rangeList
                });
            });
        }
    };

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) {
                return false;
            }

            if (Array.isArray(values.time)) {
                values.startTime = values.time[0].format('YYYY-MM-DD');
                values.endTime = values.time[1].format('YYYY-MM-DD');
            }
            delete values.time;

            /*

             {
             "type":0,  //类型，0：直降，1：折扣
             "title":"直降1元",
             "total":100,  //总数
             "startTime":"2018-05-22 12:00:00", //限制领取时间，不需要要传
             "endTime":"2018-05-25 12:00:00",
             "tag":"惠买达人",
             "rule":{
             "limit":1,  //每人限制领取数量
             "rule":1.00,  //直降金额或者折扣
             licence : {
             type : 2,  //2时间段
             value : "2018-05-25~2018-06-12"
             },
             threshold : {
             type : 1,   //0无门槛，1有门槛
             value : 200,   //门槛值
             }
             },
             rangeType : 1 ,//0全部商品，1部分商品
             "range":[170,171,172,173,174]  //商品ID
             }

             */
            values.type = Number(values.type);  //type需要数字 类型     0直降 1折扣
            values.rule = {
                limit: Number(values.limitNumber),//每人限制领取数量
                rule: (values.discount ? (values.discount / 10) : '') || Number(values.reduce),  //直降金额或者折扣
                licence: {
                    type: Number(values.date),
                    value: values.date == 2 ? (values.startTime + '~' + values.endTime) : values.dayNumber,
                },
                threshold: {
                    type: values.thresholdValue ? 1 : 0,   //0无门槛，1有门槛
                    value: Number(values.thresholdValue) || 0,   //门槛值
                }
            };
            values.rangeType = Number(values.rangeType);//0全部商品，1部分商品
            values.range = [];//商品ID
            console.log('this.state.selectedGoods', this.state.selectedGoods);
            if (values.rangeType == 1) {  //部分商品参加
                values.range = this.state.selectedGoods.map(v=>v.id);
            }

            delete values.limitNumber;
            delete values.date;
            delete values.discount;
            delete values.reduce;

            console.log(values);

            if (this.id) {
                values.id = this.id;
            }

            this.props.dispatch({
                type: 'coupon/couponSave',
                payload: values,
            }).then(res=> {
                if (res && !this.id) {  //新增才会清除表单,修改不需要
                    this.props.form.resetFields();  //重置绑定表单数据
                    this.setState({
                        selectedGoods: []
                    });
                }
            });
        });
    };

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });

    };

    changeSelectedGoods = (goods)=> {  //从弹框中获取到选中的商品
        console.log("goods", goods);
        let temp = [...this.state.selectedGoods];
        goods.forEach(v=>{
            console.log(v, 'includes',!temp.includes(v) );
            var include = false;
            temp.forEach(t=>{
                if(t.id == v.id){
                    include = true;
                }
            });
            if(!include){
                temp.push(v);
            }
        });
        this.setState({
            selectedGoods: temp
        });
    };

    removeSelected = (id)=> {  //移除选中的商品

        if (typeof id == 'undefined') {
            console.error('被移除的商品ID为空');
            return false;
        }
        let selectedGoods = [...this.state.selectedGoods];
        const result = selectedGoods.filter(v => v.id != id);
        //console.log('selectedGoods',selectedGoods, result);
        this.setState({
            selectedGoods: result
        });

    };

    render() {
        const {modalVisible, selectedGoods, detail} = this.state;
        const {getFieldDecorator, getFieldValue} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 10},
            },
        };

        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };

        const tableItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 17},
            },
        };

        console.log('detail.rule.licence.type', detail.rule.licence.type ? detail.rule.licence.type + "" : "2");
        return (
            <div>
                <Card bordered={false}>
                    <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
                        <FormItem {...formItemLayout} label="优惠券名称" help="最多支持10个字">
                            {getFieldDecorator('title', {
                                initialValue: detail.title,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入优惠券名称',
                                        max: 10
                                    },
                                ],
                            })(<Input placeholder="请输入优惠券名称"/>)}
                        </FormItem>
                        <FormItem {...formItemLayout} label="发放张数" help="单位/张">
                            {getFieldDecorator('total', {
                                initialValue: detail.total,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入发放优惠券数量',
                                    },
                                ],
                            })(<Input placeholder="请输入发放优惠券数量"/>)}
                        </FormItem>
                        <FormItem {...formItemLayout} label="使用门槛" help="订单金额满XX可使用此优惠券，不填不限制">
                            {getFieldDecorator('thresholdValue', {
                                initialValue: detail.rule.threshold.value
                            })(<Input placeholder="请输入使用门槛金额"/>)}
                        </FormItem>
                        <FormItem {...formItemLayout} label="折扣方式">
                            <div>
                                {getFieldDecorator('type', {
                                    initialValue: detail.type == 0 ? "0" : "1"
                                })(
                                    <Radio.Group>
                                        <Radio value="1">折扣方式</Radio>
                                        <Radio value="0">指定金额</Radio>
                                    </Radio.Group>
                                )}

                            </div>
                        </FormItem>
                        {
                            getFieldValue('type') === '1' ?
                                <FormItem label="折扣"  {...formItemLayout} help="请输入0-10之间的数字">
                                    {getFieldDecorator('discount', {
                                        initialValue: (detail.rule.rule * 10) || 9,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入折扣',
                                            },
                                        ],
                                    })(
                                        <Slider max={9.9} min={5} step={0.1}
                                                marks={{5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10'}}/>
                                    )}
                                </FormItem> :
                                <FormItem label="优惠金额" {...formItemLayout}>
                                    {getFieldDecorator('reduce', {
                                        initialValue: detail.rule.rule,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入优惠金额',
                                            },
                                        ],
                                    })(
                                        <Input placeholder="请输入优惠金额"/>
                                    )}
                                </FormItem>
                        }
                        <FormItem {...formItemLayout} label="每人限领">
                            {getFieldDecorator('limitNumber', {
                                initialValue: detail.rule.limit || "1",
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入发放优惠券数量',
                                    },
                                ],
                            })(
                                <Select>
                                    <Option value="1">1</Option>
                                    <Option value="2">2</Option>
                                    <Option value="3">3</Option>
                                    <Option value="4">4</Option>
                                    <Option value="5">5</Option>
                                    <Option value="10">10</Option>
                                </Select>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="用户同步标签">
                            {getFieldDecorator('tag', {
                                initialValue: detail.tag,
                                // rules: [
                                //   {
                                //     required: true,
                                //     message: '请选择用户同步标签',
                                //   },
                                // ],
                            })(
                                <Input type="text" placeholder="请输入给领券的用户打上的标签"/>
                            )}
                        </FormItem>
                        <FormItem {...formItemLayout} label="有效期">
                            {getFieldDecorator('date', {
                                initialValue: detail.rule.licence.type ? detail.rule.licence.type + "" : "2",
                            })(
                                <Radio.Group>
                                    <Radio value="2">固定时间</Radio>
                                    <Radio value="0">领券后当日起X天内有效</Radio>
                                    <Radio value="1">领券后次日起X天内家效</Radio>
                                </Radio.Group>
                            )}
                        </FormItem>
                        {
                            getFieldValue('date') != 2 ?
                                <FormItem label="天数"  {...formItemLayout}>
                                    {getFieldDecorator('dayNumber', {
                                        initialValue: detail.rule.licence.value || "",
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择天数',
                                            },
                                        ],
                                    })(
                                        <Select
                                            mode="combobox"
                                            placeholder="请选择天数"
                                        >
                                            <Option value="1">1</Option>
                                            <Option value="2">2</Option>
                                            <Option value="3">3</Option>
                                            <Option value="4">4</Option>
                                            <Option value="5">5</Option>
                                            <Option value="10">10</Option>
                                        </Select>
                                    )}
                                </FormItem>
                                :
                                <FormItem label="固定时间"  {...formItemLayout} help="包含所选择的起止日期">
                                    {getFieldDecorator('time', {
                                        initialValue: [moment(detail.startTime), moment(detail.endTime)],
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择优惠券限制使用的时间段',
                                            },
                                        ],
                                    })(
                                        <RangePicker placeholder={['开始日期', '结束日期']}/>
                                    )}
                                </FormItem>
                        }
                        <FormItem {...formItemLayout} label="可使用商品">
                            <div>
                                {getFieldDecorator('rangeType', {
                                    initialValue: detail.rangeType ? detail.rangeType + "" : '0',
                                })(
                                    <Radio.Group>
                                        <Radio value="0">全部商品</Radio>
                                        <Radio value="1">指定商品</Radio>
                                    </Radio.Group>
                                )}
                            </div>
                        </FormItem>
                        {
                            getFieldValue('rangeType') === '1' ?
                                <FormItem {...tableItemLayout} label="促销商品">
                                    <Button onClick={this.handleModalVisible}>请选择促销商品</Button>
                                    <Table
                                        style={{marginTop: '8px'}}
                                        pagination={false}
                                        columns={[
                                            {
                                                title: '图片',
                                                dataIndex: 'imgs',
                                                render(val) {
                                                    return <img src={`${val[0]}?imageView2/1/w/50`} width={50} />;
                                                },
                                            },
                                            {
                                                title: '名称',
                                                dataIndex: 'name',
                                            },
                                            {
                                                title: '库存',
                                                dataIndex: 'stock_count',
                                                align: 'right',
                                                render: val => `${val || 0}`,
                                            },
                                            {
                                                title: '原价',
                                                dataIndex: 'min_price',
                                                align: 'right',
                                                render: val => `${val || 0}元`,
                                            },
                                            {
                                                title: '折后价',
                                                align: 'right',
                                                render: (val, record)=> {
                                                    const type = getFieldValue('type');
                                                    const discount = getFieldValue('discount');
                                                    const reduce = getFieldValue('reduce');
                                                    const price = record.min_price;
                                                    let result = price;
                                                    //`${type == 2 ? (discount ? discount/10 : 1) * record.min_price : (record.min_price - reduce)}元`,
                                                    if (type == 2) {  //折扣
                                                        if (discount) {
                                                            result = (discount / 10) * price;
                                                        } else {
                                                            result = price;
                                                        }
                                                    } else {
                                                        if (reduce) {
                                                            result = price - reduce;
                                                        } else {
                                                            result = price;
                                                        }
                                                    }
                                                    return <span
                                                        style={{color: '#ff5555'}}>{Number(result).toFixed(2)}元</span>
                                                }
                                            },

                                            {
                                                title: '操作',
                                                render: (text, records)=> {
                                                    return <a onClick={()=> {
                                                        this.removeSelected(text.id)
                                                    }}>移除</a>
                                                }
                                            }
                                        ]}
                                        dataSource={selectedGoods}
                                        rowKey="id"
                                    ></Table>
                                </FormItem> : null
                        }
                        <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                            <Button style={{marginLeft: 8}}><Link to={`/sales/coupon-list`}>返回</Link></Button>
                        </FormItem>
                    </Form>
                </Card>
                <GoodsModal
                    type="coupon"
                    dispatch={this.props.dispatch}
                    modalVisible={modalVisible}
                    handleHide={this.handleModalVisible}
                    selectedRows={selectedGoods}
                    changeSelectedGoods={this.changeSelectedGoods}
                />
            </div>
        );
    }
}
